<template>
	<view class="userinfo flex flex-col h-screen">
		<NavBarVue title="个人资料"></NavBarVue>
		<view class="flex-1 overflow-hidden">
			<scroll-view scroll-y="true" class="h-full">
				<view class="card">
					<view class="card-actions">
						<!--  -->
						<FromList title="头像">
							<UpImageVue :src="anchor.headimg" :image-styles="{width: 80, height: 80}" imgKey="headimg"
								@get-url="setUrl">
							</UpImageVue>
						</FromList>
						<!--  -->
						<FromList title="名称">
							<uni-easyinput :styles="{background: 'transparent'}" style="text-align: right;" :inputBorder="false"
								:maxlength="8" v-model="anchor.name" placeholder="请输入名称(1-8个字)" />
						</FromList>
						<!--  -->
						<!-- <FromList title="昵称">
							<uni-easyinput :styles="{background: 'transparent'}" style="text-align: right;" :inputBorder="false"
								v-model="anchor.nickname" placeholder="请输入昵称(1-6个字)" />
						</FromList> -->
						<!--  -->
						<FromList title="身份证号码">
							<uni-easyinput :styles="{background: 'transparent'}" style="text-align: right;" :inputBorder="false"
								v-model="anchor.idcard" placeholder="请输入" />
						</FromList>
						<!--  -->
						<FromList title="电话">
							<view class="flex items-center">
								<text>{{anchor.phone}}</text>
							</view>
						</FromList>
						<!--  -->
						<FromList title="身份证正面" align="bottom">
							<view>
								<UpImageVue :src="anchor.idcardfront" :image-styles="{width: '690rpx', height: '300rpx'}"
									imgKey="idcardfront" @get-url="setUrl">
								</UpImageVue>
							</view>
						</FromList>
						<!--  -->
						<FromList title="身份证背面" align="bottom">
							<UpImageVue :src="anchor.idcardback" :image-styles="{width: '690rpx', height: '300rpx'}"
								imgKey="idcardback" @get-url="setUrl">
							</UpImageVue>
						</FromList>
						<FromList title="工作年限">
							<uni-easyinput :styles="{background: 'transparent'}" type="number" style="text-align: right;"
								:inputBorder="false" v-model="anchor.workyear" placeholder="请输入" />
						</FromList>
						<!-- </view>
				</view>
				<view class="card">
					<view class="card-actions"> -->
						<FromList title="个人介绍" align="bottom">
							<uni-easyinput v-model="anchor.troduction" type="textarea" placeholder="这个人很懒,还没有签名"></uni-easyinput>
						</FromList>
						<FromList title="我想对您说" align="bottom">
							<uni-easyinput v-model="anchor.wantsay" type="textarea" placeholder="这个人很懒"></uni-easyinput>
						</FromList>
						<FromList title="语音介绍">
							<view class="flex justify-between items-center">
								<uni-icons type="right" size="18" @click="handleSound"></uni-icons>
							</view>
						</FromList>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="p-30">
			<view @click="handleSubmit" class="userinfo-btn py-20">保存</view>
		</view>
		<view class="box-recording flex flex-col justify-center items-center" v-if="isRecording">
			<view class="icon-recording"></view>
			<view class="mt-8">{{audioTime}}秒</view>
		</view>
		<uni-popup ref="popupRef" type="bottom">
			<view class="bg-white rounded-t-lg p-30">
				<view class="h-[342rpx] flex flex-col">
					<view class="flex justify-center">
						<text class="font-bold text-sm">语音</text>
					</view>
					<view class="flex-1 overflow-hidden">
						<view class="w-140 bg-white rounded-lg" v-if="audioObj.extension">
							<view @click="playAudio(audioObj)"
								class="flex items-center justify-start bg-gradient-to-b from-[#94F2FF] to-[#34D3DD] rounded-full h-56 pl-10">
								<view class="icon-voice" v-if="playing"></view>
								<ImageBoxVue src="/static/user/icon_voice3.png" width="28rpx" height="28rpx" v-else></ImageBoxVue>
								<text class="text-white ml-4">{{audioObj.extension}}''</text>
							</view>
						</view>
						<view class="flex justify-center items-center bg-[#329EFF] p-20 rounded-lg mt-20" @click="handleRecord">
							<text class="text-white">{{ isRecording ? '结束录音' : '开始录音' }}</text>
						</view>
					</view>
					<view class="flex justify-center items-center bg-[#329EFF] p-20 rounded-lg mt-30" @click="handleOk">
						<text class="text-white">确定</text>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		onShow
	} from "@dcloudio/uni-app"
	import {
		debounce
	} from '@/config/publicFun.js'
	import indexApi from '@/apis/apiList/indexApi'
	import userApi from '@/apis/apiList/userApi';
	import FromList from '@/components/FromList.vue';
	import UpImageVue from "@/components/UpImage.vue";
	const recorderManager = uni.getRecorderManager()
	const userId = ref("")
	const anchor = ref({})
	const isRecording = ref(false)
	const recordList = ref([])
	let recordTimer = null
	const audioTime = ref(0)
	const popupRef = ref(false)
	const playing = ref(false)
	const audioCtx = ref(null)
	const audioObj = ref({})

	onShow(() => {
		userId.value = uni.getStorageSync('user').id
		queryAnchorInfoByMemberId()
	})

	// 获取主播信息
	const queryAnchorInfoByMemberId = () => {
		userApi.queryAnchorInfoByMemberId({
			"member.id": userId.value
		}).then(res => {
			anchor.value = res.data
			uni.setStorageSync('anchor', res.data)
		})
	}

	// 保存
	const handleSubmit = debounce(() => {
		if (!anchor.value.headimg) {
			uni.showToast({
				icon: 'none',
				title: '请上传头像'
			})
			return
		}
		if (!anchor.value.name) {
			uni.showToast({
				icon: 'none',
				title: '请输入姓名'
			})
			return
		}
		if (!anchor.value.workyear) {
			uni.showToast({
				icon: 'none',
				title: '请输入工作年限'
			})
			return
		}

		userApi.memberEditAnchorInfo({
			id: anchor.value.id,
			name: anchor.value.name,
			nickname: anchor.value.nickname,
			phone: anchor.value.phone,
			idcard: anchor.value.idcard,
			headimg: anchor.value.headimg,
			idcardfront: anchor.value.idcardfront,
			idcardback: anchor.value.idcardback,
			troduction: anchor.value.troduction,
			acadimg: anchor.value.acadimg,
			viomsg: anchor.value.viomsg || '',
			workyear: anchor.value.workyear,
			wantsay: anchor.value.wantsay || '',
			viomsg: audioObj.value.description ? `${audioObj.value.description}|${audioObj.value.extension}` : ''
		}).then(res => {
			userApi.queryAnchorInfoByMemberId({
				"member.id": userId.value
			}).then(res => {
				anchor.value = res.data
				uni.setStorageSync('anchor', res.data)
				uni.showToast({
					title: '保存成功'
				})
				uni.navigateBack(-1)
			})
		})
	})


	const handleOk = () => {
		popupRef.value.close()
	}

	// 录音回调
	recorderManager.onStop((res) => {
		console.log(res);
		if (res.tempFilePath) {
			const params = {
				filePath: res.tempFilePath,
				name: 'file',
			}
			indexApi.upLoadImage(params).then(res => {
				audioObj.value = {
					data: 'audio',
					description: `${res.data.url}`,
					extension: `${audioTime.value}`
				}
			})
			// recordList.value.unshift({
			// 	path: res.tempFilePath,
			// 	duration: Math.floor(res.duration / 1000)
			// })
		}
	})

	recorderManager.onError((err) => {
		console.error('录音错误:', err)
		uni.showToast({
			title: '录音失败',
			icon: 'none'
		})
	})

	const playAudio = (val) => {
		console.log(audioObj.value)
		if (playing.value) {
			audioCtx.value.stop();
			playing.value = false
			audioCtx.value = null
		} else {
			playing.value = true
			audioCtx.value = uni.createInnerAudioContext();
			audioCtx.value.src = audioObj.value.description; // 在线音频地址
			console.log(audioCtx.value.src);
			audioCtx.value.play();
			audioCtx.value.onEnded((res) => {
				playing.value = false
			})
		}
	}

	const handleSound = () => {
		popupRef.value.open()
	}

	const handleRecord = () => {
		if (isRecording.value) {
			stopRecord()
		} else {
			startRecord()
		}
	}

	// 开始录音
	const startRecord = () => {
		audioTime.value = 0
		recorderManager.start({
			format: 'mp3',
			duration: 600000
		})
		// showPopup.value.open()
		isRecording.value = true

		// 录音超时自动停止
		recordTimer = setInterval(() => {
			audioTime.value += 1
			console.log(audioTime.value);
			if (audioTime.value > 60) stopRecord()
		}, 1000)
	}

	// 停止录音
	const stopRecord = () => {
		recorderManager.stop()
		clearInterval(recordTimer)
		isRecording.value = false
		// showPopup.value.close()
	}

	// 选择图片
	const setUrl = (key, url) => {
		console.log(key, url);
		anchor.value[key] = url
	}
</script>

<style lang="scss" scoped>
	.t-right {
		text-align: right;
	}

	.userinfo {

		.card {
			width: 710rpx;
			margin: 20rpx auto;
			background-color: #fff;
			border-radius: 10rpx;
			padding: 20rpx;
			box-sizing: border-box;

			.title {
				font-size: 28rpx;
			}
		}

		.qian-content {
			margin-top: 20rpx;
			background-color: #f5f5f5;
			border-radius: 10rpx;
			width: 100%;
			min-height: 120px;
			padding: 20rpx;
			box-sizing: border-box;
		}

		.card-actions {
			.card-actions-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				min-height: 120rpx;

				.card-actions-item-text {
					font-size: 24rpx;
					color: #333;
					margin-right: 100rpx;
				}
			}

			.card-actions-item-col {
				display: flex;
				flex-direction: column;
				margin-bottom: 20rpx;

				.card-actions-item-text {
					font-size: 24rpx;
					color: #333;
					margin-bottom: 20rpx;
				}
			}
		}

		.userinfo-btn {
			border-radius: 60rpx;
			background: #329EFF;
			font-size: 30rpx;
			color: #fff;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}

	.icon-voice {
		animation-name: voiceExample;
		/* 引用上面定义的@keyframes */
		animation-duration: 3s;
		/* 动画持续时间 */
		animation-iteration-count: infinite;
		/* 无限循环 */
		background: url(/static/user/icon_voice1.png) no-repeat;
		background-size: contain;
		width: 28rpx;
		height: 30rpx;
	}

	@keyframes voiceExample {
		0% {
			background: url(/static/user/icon_voice1.png) no-repeat;
			background-size: contain;
			width: 28rpx;
			height: 30rpx;
		}

		50% {
			background: url(/static/user/icon_voice2.png) no-repeat;
			background-size: contain;
			width: 28rpx;
			height: 30rpx;
		}

		100% {
			background: url(/static/user/icon_voice3.png) no-repeat;
			background-size: cover;
			width: 28rpx;
			height: 30rpx;
		}
	}

	.box-recording {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);

		.icon-recording {
			animation-name: example;
			/* 引用上面定义的@keyframes */
			animation-duration: 2s;
			/* 动画持续时间 */
			animation-iteration-count: infinite;
			/* 无限循环 */
			background: url(/static/community/recording1.png) no-repeat;
			background-size: contain;
			width: 160rpx;
			height: 160rpx;
		}

		@keyframes example {
			0% {
				background: url(/static/community/recording1.png) no-repeat;
				background-size: contain;
				width: 160rpx;
				height: 160rpx;
			}

			25% {
				background: url(/static/community/recording2.png) no-repeat;
				background-size: contain;
				width: 160rpx;
				height: 160rpx;
			}

			50% {
				background: url(/static/community/recording3.png) no-repeat;
				background-size: contain;
				width: 160rpx;
				height: 160rpx;
			}

			100% {
				background: url(/static/community/recording4.png) no-repeat;
				background-size: cover;
				width: 160rpx;
				height: 160rpx;
			}
		}
	}
</style>